var express = require('express');
var router = express.Router();
const {
  dealUpload
} = require('../utils/upload')
const {
  readBlog,
  getBlogList,
  register,
  valiateUser
} = require('../db/index')
/* GET home page. */
router
  .get('/login', (req, res, next) => {
    res.render('login')
    // res.redirect('/blogList')
  })
  

  .post('/login', async (req, res, next) => {
    let name = req.body.name || ''
    let password = req.body.password || ''
    if (await valiateUser(name, password)) {
      res.cookie('LoginStatus', true, {
        expires: new Date(new Date().getTime() + 1000 * 60)
      })
      res.send ({
        code: 0,
        message: 'success login'
      })
    } else {
      res.send ({
        code: -100,
        message: 'failed login'
      })
    }
  })

  .post('/register', async (req, res, next) => {
    let name = req.body.name || ''
    let password = req.body.password || ''
    const boo = await register(name, password)
    console.log('register(name, password)', boo)
    if (boo) {
      res.send({
        code: 0,
        message: 'Success register'
      })
    } else {
      res.send({
        code: -100,
        message: 'failed register'
      })
    }
  })


  // 上传文件
  .get('/upload', (req, res, next) => {
     res.render('upload')
  })
  .post('/upload', (req, res, next)  => {
    dealUpload(req, res, next).then(() => res.send('uploadSuccess!!!'))
  })

  // 删除某篇博客
  .post('/delete/blog/:blogId', async (ctx, next) => {

  })

  // 修改博客的分类
  .post('/modify/blog/:blogId/:kindName', async (ctx, next) => {

  })

  // 查看某一篇博客
  .get('/blog/:blogId',async (req, res, next) => {
    let blogId = req.params.blogId
    console.log('blogOd', blogId)
    let content = await readBlog(blogId)
    res.render('detail', {
      result: content.content
    })
  })

  // 查看博客列表
  .get('/blogList', async (req, res, next) => {
    const result = await getBlogList('/')
    res.render('blogList', {
      result
    })
  })


module.exports = router;